package br.com.daniele.controller;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;

@Controller
public class FileDownloadController extends HttpServlet implements Servlet{
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final int BUFSIZE = 4096;
    private String filePath;
    private String nameFileReference;
    private String property = System.getProperty("user.dir");
    
    public void init() {
    	
    	SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy");
		String dataAtual = sdf.format(new Date());
    	
        // the file data.xls is under web application folder
        filePath = property + File.separator + dataAtual;
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	String fileNumberDownload = request.getParameter("fileName");
    	nameFileReference = filePath+fileNumberDownload+".zip";
    	
        File file = new File(nameFileReference);
        int length   = 0;
        ServletOutputStream outStream = response.getOutputStream();
        ServletContext context  = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(nameFileReference);
        
        // sets response content type
        if (mimetype == null) {
            mimetype = "application/zip";
        }
        
        response.setContentType(mimetype);
        response.setContentLength((int)file.length());
        String fileName = (new File(nameFileReference)).getName();
        
        // sets HTTP header
        //response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setHeader("Content-Disposition", "attachment; filename="+ fileName);
        
        byte[] byteBuffer = new byte[BUFSIZE];
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        
        // reads the file's bytes and writes them to the response stream
        while ((in != null) && ((length = in.read(byteBuffer)) != -1))
        {
            outStream.write(byteBuffer,0,length);
        }
        
        in.close();
        outStream.close();
        
        
    }
	
	
	

}
